/**
 * 
 */
package org.aman.shiro.common.shiro;

import org.aman.shiro.entity.User;
import org.aman.shiro.service.UserManager;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @Copyright: 本内容仅限于重庆爱赢科技有限公司内部使用，禁止转发. 
 * @Author: daijiangguo 2014-6-10 下午2:00:03 
 * @Version: $Id$
 * @Desc: <p></p>
 */
public class MyRealm extends AuthorizingRealm {

    /* 
     *  授权信息 
     * (non-Javadoc)
     * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo result = new SimpleAuthorizationInfo();
        // 获取当前登录的用户
        User user = (User) super.getAvailablePrincipal(principals);

        result.addStringPermission("/"+user.getUserName());
        
        return result;
    }

    /* 认证信息
     * (non-Javadoc)
     * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String userName = token.getUsername();
        
        if (userName != null && !"".equals(userName)) {
            User user = new UserManager().findUserByUserName(userName);
            if(user == null){
                throw new AccountException("用户不存在！");
            }else{
                return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
            }
        }
        return null;
    }

}
